package com.mf.morefun.util;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.mf.morefun.R;
import com.mf.morefun.bean.EventMessageBean;
import com.mf.morefun.bean.ResultBean;
import com.mf.morefun.constant.Configuration;
import com.mf.morefun.requestbean.RequestFlowerBean;
import com.mf.morefun.requestbean.RequestSendFlowerBean;
import com.mf.morefun.ui.moreread.DoTestActivity;
import com.mf.morefun.ui.moreread.ListenRecordActivity;
import com.mf.morefun.ui.moreread.MoreReadDetailActivity;
import com.mf.morefun.ui.myclass.CreateClassHomeWorkActivity;
import com.mf.morefun.widget.NetErrorPop;
import com.zhcx.zhcxlibrary.utils.AppManager;
import com.zhcx.zhcxlibrary.utils.StringUtils;
import com.zhcx.zhcxlibrary.utils.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;
/*
    获取花数量的接口工具类
 */
public class SendStarOrFlowerNet {
    private Context mContext;
    private StarView starView;
    private LinearLayout lyContent;
    private String bookId;
    public SendStarOrFlowerNet(Context mContext, LinearLayout lyContent) {
        this.mContext = mContext;
        this.lyContent = lyContent;
    }
    Handler handler = new Handler();
    Runnable runnable = new Runnable() {

        @Override
        public void run() {
            if (null != starView){
                Log.d("123", "-------run------" + starView.getStarNums());
                // TODO Auto-generated method stub
                if (!starView.isRunning()) {
                    starView.start();
                }
                starView.addStars(25);
                handler.postDelayed(runnable, 200);
                if (starView.getStarNums() >= StarView.MAX_NUM) {
                    handler.removeCallbacksAndMessages(null);
                }
            }
        }
    };
    /**
     *
     * @param flower 数量
     * @param userId
     * @param workId 书ID
     * @param rewoard 星星类型
     * @param type case  work        = "1"//作品录音
    case homework    = "2"//作业录音
    case test        = "3"//测试
    case moerduo     = "4"//磨耳朵
    case listen      = "5"//听讲解
    case original    = "6"//听原音
    case share       = "7"//分享
     */
    public void initGetFlower(int flower, String userId, String workId, String rewoard, String type) {
        bookId = workId;
        RequestParams params = new RequestParams(Configuration.HOST + Configuration.SENDFLOWER);
        RequestFlowerBean requestSendFlowerBean = new RequestFlowerBean();
        requestSendFlowerBean.setFromType("3");
        requestSendFlowerBean.setRewardType(rewoard);//星星类型
        requestSendFlowerBean.setRewardNumber(flower);//数量
        RequestFlowerBean.StudentBean studentBean = new RequestFlowerBean.StudentBean();
        studentBean.setId(userId);
        requestSendFlowerBean.setStudent(studentBean);
        RequestFlowerBean.WorkBean teacherBean = new RequestFlowerBean.WorkBean();
        teacherBean.setId(workId);//书id
        requestSendFlowerBean.setWorkId(teacherBean);
        requestSendFlowerBean.setWorkHomeworkType(type);
        params.setBodyContent(JSON.toJSONString(requestSendFlowerBean));
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if (!StringUtils.isEmpty(result)) {
                    ResultBean resultBean = JSON.parseObject(result, ResultBean.class);
                    if (resultBean.getErrorCode() != 0) {
                        if (!type.equals("4") && null != lyContent){
                            Message msg = new Message();
                            msg.what = 103;
                            msg.obj = resultBean.getMessage();
                            msg.arg1 = flower;
                            msg.arg2 = Integer.parseInt(type);
                            mHandler.sendMessage(msg);
                        }
                    }else {
                        if (!type.equals("4") && null != lyContent){
                            Message msg = new Message();
                            msg.what = 102;
                            msg.obj = type;
                            msg.arg1 = flower;
                            msg.arg2 = Integer.parseInt(type);
                            mHandler.sendMessage(msg);
                        }
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Message msg = new Message();
                msg.what = 101;
                mHandler.sendMessage(msg);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }


    private PopupWindow mUserPop;

    private void showFinishPop(String type, int flower, int mType) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.layout_popfinish, null);
        RelativeLayout rlBg = view.findViewById(R.id.rl_bg);
        rlBg.getBackground().setAlpha(100);
        TextView tv_back = view.findViewById(R.id.tv_back);
        TextView tv_share = view.findViewById(R.id.tv_share);
        TextView tv_unit = view.findViewById(R.id.tv_unit);
        TextView tv_num = view.findViewById(R.id.tv_num);
        TextView tv_type = view.findViewById(R.id.tv_type);
        ImageView iv_smallleft = view.findViewById(R.id.iv_smallleft);
        ImageView iv_big = view.findViewById(R.id.iv_big);
        ImageView iv_smallright = view.findViewById(R.id.iv_smallright);
        if (StringUtils.isEmpty(getTypeInfo(type))){
            tv_type.setText(type);
            tv_unit.setVisibility(View.GONE);
            tv_num.setVisibility(View.GONE);
        }else {
            tv_unit.setVisibility(View.VISIBLE);
            tv_num.setVisibility(View.VISIBLE);
            tv_type.setText("本次获得" + getTypeInfo(type) + "奖励");
            tv_num.setText(flower + "");
            if (type.equals("7")){
                iv_smallleft.setImageResource(R.mipmap.mine_flower_icon);
                iv_big.setImageResource(R.mipmap.mine_flower_icon);
                iv_smallright.setImageResource(R.mipmap.mine_flower_icon);
                tv_unit.setText("朵花");
            }else {
                iv_smallleft.setImageResource(R.mipmap.wujiaoxing);
                iv_big.setImageResource(R.mipmap.wujiaoxing);
                iv_smallright.setImageResource(R.mipmap.wujiaoxing);
                tv_unit.setText("颗星星");
            }
        }
        tv_back.setTextColor(0xffffffff);
        tv_back.setBackgroundResource(R.drawable.blue_shapes);
        tv_share.setVisibility(View.GONE);
        tv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mUserPop.dismiss();
                mUserPop = null;
                Intent mIntent = new Intent();
                mIntent.putExtra("BOOKID", bookId);
                mIntent.setAction("REFRESHPAGE");
                mContext.sendBroadcast(mIntent);
                if (mType == 5){
                    try {
                        AppManager.getAppManager().finishActivity(mContext.getClass());
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }else if(mType == 3){
                    Intent intent = new Intent(mContext, CreateClassHomeWorkActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
                    intent.putExtra("BOOKID", bookId);
                    mContext.startActivity(intent);
                    try {
                        AppManager.getAppManager().finishActivity(mContext.getClass());
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }
        });
        mUserPop = new PopupWindow(view, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
        mUserPop.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        mUserPop.setBackgroundDrawable(new BitmapDrawable());
        mUserPop.setFocusable(true);
        mUserPop.update();
        mUserPop.showAtLocation(view, Gravity.CENTER, 0, 0);
        mUserPop.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                mUserPop.dismiss();
                mUserPop = null;
            }
        });
    }

    private String getTypeInfo(String type) {
        String info = "";
        switch (type){
            case "1":
                info = "作品";
                break;
            case "2":
                info = "作业";
                break;
            case "3":
                info = "测试";
                break;
            case "4":
                info = "磨耳朵";
                break;
            case "5":
                info = "听讲解";
                break;
            case "6":
                info = "听原音";
                break;
            case "7":
                info = "分享";
                break;
        }
        return info;
    }

    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 101:
                    NetErrorPop errorPop = new NetErrorPop(mContext);
                    errorPop.showPop("");
                    break;
                case 102:
                    startStar((String) msg.obj, msg.arg1, msg.arg2);
                    break;
                case 103:
                    startStar((String) msg.obj, msg.arg1, msg.arg2);
                    break;
            }
        }
    };

    //关闭
    public void stopAnim(){
        if (null != starView && starView.isRunning()){
            starView.stop();
        }
    }
    //开始星星
    private void startStar(String type, int flower, int mType){
        if (type.equals("7")){
            starView = new StarView(mContext, "1");
        }else {
            starView = new StarView(mContext, "0");
        }
        lyContent.removeAllViews();
        lyContent.addView(starView);
        handler.postDelayed(runnable, 0);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                starView.stop();
                lyContent.removeAllViews();
                if (type.equals("1") || type.equals("2")){
                    EventMessageBean messageBean = new EventMessageBean();
                    if (StringUtils.isEmpty(getTypeInfo(type))){
                        messageBean.setType(1088);
                        messageBean.setFileName(type);
                    }else {
                        messageBean.setType(1099);
                        messageBean.setFileName(getTypeInfo(type));
                    }
                    EventBus.getDefault().post(messageBean);
                }else {
                    try {
                        showFinishPop(type, flower, mType);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }
        }, 5000);
    }

}
